package map.android.baidu.carpool.page.usercenter;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.baidu.components.api.extra.APIProxy;
import com.baidu.lbs.net.http.model.ComNetData;
import com.baidu.lbs.net.http.model.IDataStatusChangedListener;
import map.android.baidu.carpool.R;
import map.android.baidu.carpool.data.impl.DiscountListData;
import map.android.baidu.carpool.model.DiscountItem;
import map.android.baidu.carpool.page.CarpoolBasePage;
import map.android.baidu.carpool.page.pay.OrderPayPage;
import map.android.baidu.carpool.response.DiscountListResponse;
import map.android.baidu.carpool.utils.SafeUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by zhangtongyu on 15/4/7.
 * 优惠券列表页面
 */
public class DiscountListPage extends CarpoolBasePage{
    private Context mContext;
    private Resources mRes;
    private LayoutInflater mInflater;

    private View mView;
    private ListView mDiscountLv;

    private View mFooterView;
    private TextView mFooterViewTv;

    private View mNoDiscountHeader;

    private DiscountItemAdapter mDiscountAdapter;

    private static String CAN_USE_DISCOUNT = "1";
    private static String GUO_QI_DISCOUNT = "0";
    private static String GUOQI_TITLE = "-1";

    private Bundle mBundle;

    private DiscountListResponse mResponse;
    private IDataStatusChangedListener<DiscountListResponse> listener = new IDataStatusChangedListener<DiscountListResponse>() {
        @Override
        public void onDataStatusChanged(ComNetData<DiscountListResponse> data, DiscountListResponse response, int dataStatus) {
            if (dataStatus == ComNetData.DATA_STATUS_SUCCESS) {
                if (response != null && response.data != null) {
                    updateData(response);
                    showLoadingDialog(false);
                } else {
                    mDiscountLv.addHeaderView(mNoDiscountHeader);
                    mDiscountLv.setAdapter(mDiscountAdapter);
                    showLoadingDialog(false);
                }
            } else {
                mDiscountLv.addHeaderView(mNoDiscountHeader);
                mDiscountLv.setAdapter(mDiscountAdapter);
                showLoadingDialog(false);
            }
        }
    };


    private void updateData(DiscountListResponse response) {
        if (response.data.useList != null && response.data.useList.size() != 0) {
            for (int index = 0; index < response.data.useList.size(); index++){
                if(response.data.useList.get(index) != null){
                    response.data.useList.get(index).type = CAN_USE_DISCOUNT;
                }
            }
            mDiscountAdapter.setListData(response.data.useList, false);
        } else {
            mDiscountLv.addHeaderView(mNoDiscountHeader);
        }

        if (response.data.disableList != null && response.data.disableList.size() != 0) {
                addFooterView(response);
        } else {
        }
        mDiscountLv.setAdapter(mDiscountAdapter);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        mContext = APIProxy.res().getBaseActivity();
        mRes = APIProxy.res().getResources();
        mInflater = APIProxy.res().getInflater();
        if (mView == null) {
            mBundle = getArguments();
            mView = mInflater.inflate(R.layout.layout_page_discount_list, null);
            initTitleBar(mView);
            initView(mView);
            initListView(mView);
        } else {
            ViewGroup parent = (ViewGroup) mView.getParent();
            if (parent != null) {
                parent.removeView(mView);
            }
        }
        return mView;
    }

    private void initView(View mView) {
        mNoDiscountHeader = mInflater.inflate(R.layout.layout_discount_header, null, false);
    }

    private void initTitleBar(View mView) {
        ImageView backBt = (ImageView) mView.findViewById(R.id.left_view);
        TextView titleTv = (TextView) mView.findViewById(R.id.center_view);

        backBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getTask().goBack(mBundle);
            }
        });
        backBt.setVisibility(View.VISIBLE);

        titleTv.setText("优惠券");
        titleTv.setVisibility(View.VISIBLE);
    }

    private void initListView(View mView) {
        LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        mDiscountLv = (ListView) mView.findViewById(R.id.lv_discount_can_use_and_disable);
        mDiscountLv.setLayoutParams(params1);
        mDiscountLv.setBackgroundColor(0xededed);
        mDiscountLv.setVerticalScrollBarEnabled(false);
        mDiscountLv.setDividerHeight(0);
        mDiscountLv.setHeaderDividersEnabled(false);
        mDiscountLv.setFooterDividersEnabled(false);
        mDiscountLv.setCacheColorHint(0x00000000);
        mDiscountLv.setSelector(new ColorDrawable(Color.TRANSPARENT));
        mDiscountLv.setFadingEdgeLength(0);
        mDiscountAdapter = new DiscountItemAdapter(mContext);

        requestDiscountListData();
    }

    private void addFooterView(final DiscountListResponse discountListResponse){
        mFooterView = APIProxy.res().inflate(R.layout.layout_discount_guoqi_notice);
        mFooterViewTv = (TextView) mFooterView.findViewById(R.id.car_coupon_listview_title);
        String exchange = getResources().getString(R.string.coupon_time_out);
        mFooterViewTv.setText(Html.fromHtml(exchange));
        mFooterView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DiscountItem guoqiNoticeItem = new DiscountItem();
                guoqiNoticeItem.type = GUOQI_TITLE;
                mDiscountAdapter.addTitleItem(guoqiNoticeItem);
                for (int index = 0; index < discountListResponse.data.disableList.size(); index++){
                    if(discountListResponse.data.disableList.get(index) != null){
                        discountListResponse.data.disableList.get(index).type = GUO_QI_DISCOUNT;
                    }
                }
                mDiscountAdapter.setListData(discountListResponse.data.disableList, false);

                mDiscountLv.removeFooterView(mFooterView);
            }
        });
        mDiscountLv.addFooterView(mFooterView);
        mFooterView.setVisibility(View.VISIBLE);
    }

    private void requestDiscountListData() {
        DiscountListData discountListData = new DiscountListData(mContext);
        discountListData.post(listener);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public boolean onBackPressed() {
        goBack(mBundle);
        return true;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    public class DiscountItemAdapter extends BaseAdapter {

        private Context mContext;
        private LayoutInflater mInflater;
        private Resources mRes;
        private List<DiscountItem> listData;
        private DiscountItemViewHolder mViewHolder;

        /**
         * @param context  1:可用优惠券  0:过期优惠券 -1:过期优惠券的查看提示
         */
        public DiscountItemAdapter(Context context) {
            mContext = context;
            mInflater = APIProxy.res().getInflater();
            mRes = APIProxy.res().getResources();
            listData = new ArrayList<DiscountItem>();
        }

        /**
         * @param list      数据
         * @param needClear 是否需要清除之前的数据
         */
        public void setListData(List<DiscountItem> list, boolean needClear) {
            if (needClear) {
                listData.clear();
            }
            listData.addAll(list);
            notifyDataSetChanged();
        }


        @Override
        public int getCount() {
            if (listData != null) {
                return listData.size();
            } else {
                return 0;
            }
        }

        @Override
        public Object getItem(int position) {
            if (listData != null) {
                return listData.get(position);
            } else {
                return null;
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final DiscountItem item = listData.get(position);
            if (convertView == null || convertView.getTag() == null) {
                mViewHolder = new DiscountItemViewHolder();
                if (GUOQI_TITLE.equals(item.type)) {
                    convertView = mInflater.inflate(R.layout.layout_discount_guoqi_notice, null);
                    return convertView;
                } else {
                    convertView = mInflater.inflate(R.layout.layout_item_discount, null);
                    if (position == 0) {
                        convertView.setPadding(0, 10, 0, 0);
                    }
                    mViewHolder.discountPriceIconTv = (TextView) convertView.findViewById(R.id.tv_item_discount_icon);
                    mViewHolder.discountStyleShang = convertView.findViewById(R.id.v_discount_shang);
                    mViewHolder.discountPriceTv = (TextView) convertView.findViewById(R.id.tv_item_discount_price);
                    mViewHolder.discountTitleTv = (TextView) convertView.findViewById(R.id.tv_item_discount_title);
                    mViewHolder.discountLimitTimeTv = (TextView) convertView.findViewById(R.id.tv_item_discount_user_time);
                }
            } else {
                Object tag = convertView.getTag();
                if (tag instanceof DiscountItemViewHolder) {
                    mViewHolder = (DiscountItemViewHolder) tag;
                }
            }
            if (GUO_QI_DISCOUNT.equals(item.type)) {
                SafeUtils.safeSetBackground(R.drawable.discount_guoqi_bg, mViewHolder.discountStyleShang);
                mViewHolder.discountPriceIconTv.setTextColor(mRes.getColor(R.color.discount_guoqi_gray));
                mViewHolder.discountPriceTv.setTextColor(mRes.getColor(R.color.discount_guoqi_gray));
                mViewHolder.discountTitleTv.setTextColor(mRes.getColor(R.color.discount_guoqi_gray));
                mViewHolder.discountLimitTimeTv.setTextColor(mRes.getColor(R.color.discount_guoqi_gray));
            } else if (CAN_USE_DISCOUNT.equals(item.type)) {
                SafeUtils.safeSetBackground(R.drawable.discount_shang_bg, mViewHolder.discountStyleShang);
            }
            if(CAN_USE_DISCOUNT.equals(item.type) || GUO_QI_DISCOUNT.equals(item.type)) {
                mViewHolder.discountPriceTv.setText(item.price);
                mViewHolder.discountTitleTv.setText(item.name);

                SimpleDateFormat startFormat = new SimpleDateFormat("yyyy.MM.dd");
                SimpleDateFormat endFormat = new SimpleDateFormat("MM.dd");
                StringBuilder sb = new StringBuilder();
                if (!TextUtils.isEmpty(item.startTime)) {
                    String startTimeString = startFormat.format(new Date(Long.parseLong(item.startTime) * 1000));
                    sb.append(startTimeString);
                }
                if (!TextUtils.isEmpty(item.endTime)) {
                    sb.append("-");
                    String endTimeString = startFormat.format(new Date(Long.parseLong(item.endTime) * 1000));
                    sb.append(endTimeString);
                }
                mViewHolder.discountLimitTimeTv.setText("有效期：" + sb.toString());
            }
            if(CAN_USE_DISCOUNT.equals(item.type)){
                if(mBundle != null && mBundle.containsKey("discount")){
                    DiscountItem choosedDiscount = (DiscountItem) mBundle.getSerializable("discount");
                    if(item.discountId.equals(choosedDiscount.discountId)){
                        SafeUtils.safeSetBackground(R.drawable.discount_shang_xuanzhong_bg, mViewHolder.discountStyleShang);
                        mViewHolder.discountPriceIconTv.setTextColor(mRes.getColor(R.color.car_text_orange));
                        mViewHolder.discountPriceTv.setTextColor(mRes.getColor(R.color.car_text_orange));
                        mViewHolder.discountTitleTv.setTextColor(mRes.getColor(R.color.car_text_orange));
                        mViewHolder.discountLimitTimeTv.setTextColor(mRes.getColor(R.color.car_text_orange));
                    } else {
                        SafeUtils.safeSetBackground(R.drawable.discount_shang_bg, mViewHolder.discountStyleShang);
                        mViewHolder.discountPriceIconTv.setTextColor(mRes.getColor(R.color.carpool_invoice_text_color));
                        mViewHolder.discountPriceTv.setTextColor(mRes.getColor(R.color.carpool_invoice_text_edit));
                        mViewHolder.discountTitleTv.setTextColor(mRes.getColor(R.color.carpool_text_gray_dack));
                        mViewHolder.discountLimitTimeTv.setTextColor(mRes.getColor(R.color.carpool_text_gray_dack));
                    }
                }
            }
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(GUO_QI_DISCOUNT.equals(item.type)){
                        return;
                    }
                    if(GUOQI_TITLE.equals(item.type)){
                        return;
                    }
                    if(mBundle == null){
                        return;
                    }
                    if(!mBundle.containsKey("from")){
                        return;
                    }
                    if(!mBundle.containsKey("orderId")){
                        return;
                    }
                    if(OrderPayPage.class.getName().equals(mBundle.getString("from"))){
                        //从支付页进入  需要选择优惠券
                        if(mBundle.containsKey("discount")){
                            DiscountItem choosedDiscountItem = (DiscountItem) mBundle.getSerializable("discount");
                            if(item.discountId.equals(choosedDiscountItem.discountId)){
                                mBundle.putBoolean("removeDiscount", true);
                                mBundle.remove("discount");
                                SafeUtils.safeSetBackground(R.drawable.discount_shang_bg, mViewHolder.discountStyleShang);
                                mViewHolder.discountPriceIconTv.setTextColor(mRes.getColor(R.color.carpool_invoice_text_color));
                                mViewHolder.discountPriceTv.setTextColor(mRes.getColor(R.color.carpool_invoice_text_edit));
                                mViewHolder.discountTitleTv.setTextColor(mRes.getColor(R.color.carpool_text_gray_dack));
                                mViewHolder.discountLimitTimeTv.setTextColor(mRes.getColor(R.color.carpool_text_gray_dack));
                            } else {
                                mBundle.putSerializable("discount", item);
                                if(mBundle.containsKey("removeDiscount")) {
                                    mBundle.remove("removeDiscount");
                                }
                                goBack(mBundle);
                            }
                        } else {
                            mBundle.putSerializable("discount", item);
                            if(mBundle.containsKey("removeDiscount")) {
                                mBundle.remove("removeDiscount");
                            }
                            goBack(mBundle);
                        }
                    } else {
                        return;
                    }
                }
            });
            return convertView;
        }

        public void addTitleItem(DiscountItem item) {
            listData.add(item);
            notifyDataSetChanged();
        }

    }

    public class DiscountItemViewHolder {
        TextView discountPriceIconTv;
        TextView discountPriceTv;
        TextView discountTitleTv;
        TextView discountLimitTimeTv;
        View discountStyleShang;
    }

}
